package com.order.manager.controller.Collect;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.order.manager.Model.CollectInfo;
import com.order.manager.Model.other.RestBean;
import com.order.manager.service.impl.CollectInfoServiceImpl;
import com.order.manager.util.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/api/collect")
public class CollectController {

    @Resource
    CollectInfoServiceImpl collectInfoService;

    @Resource
    JwtUtil jwtUtil;

    @RequestMapping("/choose/{shopId}")
    public RestBean collectByUserShop(HttpServletRequest request, @PathVariable String shopId) {
        String uuid = jwtUtil.getJwtUsername(request);
        return collectInfoService.getOne(new QueryWrapper<CollectInfo>().eq("collect_shop_id", shopId)
                .eq("collect_user_id", uuid)) != null
                ? RestBean.success() : RestBean.failure(403, "该用户未关注该店铺");
    }

    @RequestMapping("/follow/{shopId}")
    public RestBean followShop(HttpServletRequest request, @PathVariable String shopId) {
        String uuid = jwtUtil.getJwtUsername(request);
        CollectInfo collectInfo = collectInfoService.getOne(new QueryWrapper<CollectInfo>().eq("collect_shop_id", shopId)
                .eq("collect_user_id", uuid));
        if (collectInfo == null) {
            CollectInfo collect = new CollectInfo();
            collect.setInputTime(new Date());
            collect.setCollectShopId(shopId);
            collect.setCollectUserId(uuid);
            return collectInfoService.save(collect) ? RestBean.success(collectInfo) : RestBean.failure(500, "收藏失败");
        }
        return RestBean.failure(403,"你已关注该店铺");
    }

    @RequestMapping("/cancel/follow/{shopId}")
    public RestBean cancelFollowShop(HttpServletRequest request, @PathVariable String shopId) {
        String uuid = jwtUtil.getJwtUsername(request);
        CollectInfo collectInfo = collectInfoService.getOne(new QueryWrapper<CollectInfo>().eq("collect_shop_id", shopId)
                .eq("collect_user_id", uuid));
        if (collectInfo == null)
            return RestBean.failure(403,"你尚未收藏该店铺");
        return collectInfoService.removeById(collectInfo)? RestBean.success(collectInfo)
                : RestBean.failure(500, "取消收藏失败");
    }


}
